<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="true" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>请假申请管理</title>
    <script src="vue2_resource/vue@2.6.14.js"></script>
    <link rel="stylesheet" href="vue2_resource/index.css">
    <script src="vue2_resource/elementui.js"></script>
    <script src="vue2_resource/axios.min.js"></script>
    <script src="vue2_resource/axiosWrapper.js"></script>

    <style>
        body {
            background-color: #f0f2f5;
            padding: 20px;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
        }

        .el-card {
            margin-bottom: 20px;
        }

        .filter-section {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 15px;
        }

        .el-table {
            width: 100%;
            overflow-x: auto;
        }

        .el-table .cell {
            white-space: nowrap;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="filter-section">
<%--            <el-input--%>
<%--                    v-model="searchUserId"--%>
<%--                    placeholder="搜索用户ID"--%>
<%--                    style="width: 200px;">--%>
<%--            </el-input>--%>
<%--            <el-button type="primary" icon="el-icon-search" @click="handleSearch" size="small">搜索</el-button>--%>
<%--            <el-button type="info" icon="el-icon-refresh" @click="resetSearch" size="small">重置</el-button>--%>
            <el-button type="success" icon="el-icon-plus" @click="openAddLeaveRequestDialog" size="small"
                       v-if="userRole === 'user'">添加请假申请
            </el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" size="small"
                       :disabled="selectedLeaveRequests.length === 0">批量删除
            </el-button>
        </div>
    </el-card>

    <el-card>
        <el-table :data="leaveRequests" style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="leaveType" label="请假类型" width="120"></el-table-column>
            <el-table-column prop="startDate" label="开始日期" width="160"></el-table-column>
            <el-table-column prop="endDate" label="结束日期" width="160"></el-table-column>
            <el-table-column prop="reason" label="请假原因" width="200"></el-table-column>
            <el-table-column prop="status" label="状态" width="120">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 'approved' ? 'success' : (scope.row.status === 'rejected' ? 'danger' : 'info')">
                        {{ scope.row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="approverId" label="审批人ID" width="100"></el-table-column>
            <el-table-column prop="approveTime" label="审批时间" width="160"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="160"></el-table-column>
            <el-table-column label="操作" width="300" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit"
                               @click="openEditLeaveRequestDialog(scope.row)" v-if="userRole === 'user' && scope.row.status === 'pending'">
                        编辑
                    </el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                    </el-button>
                    <el-button size="mini" type="success" icon="el-icon-check" @click="approveLeaveRequest(scope.row)"
                               v-if="userRole === 'admin' && scope.row.status === 'pending'">
                        批准
                    </el-button>
                    <el-button size="mini" type="warning" icon="el-icon-close" @click="rejectLeaveRequest(scope.row)"
                               v-if="userRole === 'admin' && scope.row.status === 'pending'">
                        拒绝
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div style="margin-top: 20px;">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalLeaveRequests">
            </el-pagination>
        </div>
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
        <el-form :model="currentLeaveRequest" label-width="100px">
            <el-form-item label="用户ID" v-if="userRole === 'user'">
                <el-input v-model="currentLeaveRequest.userId" disabled></el-input>
            </el-form-item>
            <el-form-item label="请假类型">
                <el-select v-model="currentLeaveRequest.leaveType" placeholder="请选择请假类型">
                    <el-option
                            v-for="item in leaveTypes"
                            :key="item.id"
                            :label="item.typeName"
                            :value="item.typeName">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="开始日期">
                <el-date-picker v-model="currentLeaveRequest.startDate" type="datetime"
                                value-format="yyyy-MM-dd'T'HH:mm:ss"
                                placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束日期">
                <el-date-picker v-model="currentLeaveRequest.endDate" type="datetime"
                                value-format="yyyy-MM-dd'T'HH:mm:ss"
                                placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="请假原因">
                <el-input v-model="currentLeaveRequest.reason" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="审批人ID" v-if="userRole === 'admin'">
                <el-input v-model="currentLeaveRequest.approverId" readonly></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" size="small" icon="el-icon-close">取 消</el-button>
            <el-button type="primary" @click="saveLeaveRequest" size="small" icon="el-icon-check">确 定</el-button>
        </div>
    </el-dialog>
</div>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                leaveRequests: [],
                currentPage: 1,
                pageSize: 10,
                totalLeaveRequests: 0,
                dialogVisible: false,
                dialogTitle: '添加请假申请',
                currentLeaveRequest: {
                    id: null,
                    userId: '',
                    leaveType: '',
                    startDate: '',
                    endDate: '',
                    reason: '',
                    status: 'pending',
                    approverId: '',
                    approveTime: '',
                    createTime: '',
                    updateTime: ''
                },
                searchUserId: '',
                selectedLeaveRequests: [],
                userRole: 'user', // 默认用户角色为普通用户
                userInfo: {},
                leaveTypes: [] // 请假类型列表
            }
        },
        mounted() {
            this.getUserInfo();
            this.fetchLeaveRequests();
            this.fetchLeaveTypes();
        },
        methods: {
            fetchLeaveRequests() {
                console.log("fetchLeaveRequests() - userRole: " + this.userRole);
                console.log(this.userInfo);

                const params = {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    userId: this.userRole === 'admin' ? null : this.userInfo.id,
                    leaveType: '',
                    status: ''
                };

                axiosWrapper.get('/api/leaveRequests/page', { params })
                    .then(response => {
                        this.leaveRequests = response.data.list;
                        this.totalLeaveRequests = response.data.total;
                    })
                    .catch(error => {
                        console.error('Error fetching leave requests:', error);
                        this.$message.error('获取请假申请列表失败');
                    });
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.fetchLeaveRequests();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchLeaveRequests();
            },
            handleSearch() {
                this.currentPage = 1;
                this.fetchLeaveRequests();
            },
            resetSearch() {
                this.searchUserId = '';
                this.currentPage = 1;
                this.fetchLeaveRequests();
            },
            openAddLeaveRequestDialog() {
                this.dialogTitle = '添加请假申请';
                this.currentLeaveRequest = {
                    id: null,
                    userId: this.userInfo.id,
                    leaveType: '',
                    startDate: '',
                    endDate: '',
                    reason: '',
                    status: 'pending',
                    approverId: '',
                    approveTime: '',
                    createTime: '',
                    updateTime: ''
                };
                this.dialogVisible = true;
            },
            openEditLeaveRequestDialog(leaveRequest) {
                this.dialogTitle = '编辑请假申请';
                this.currentLeaveRequest = {...leaveRequest};
                this.dialogVisible = true;
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除该请假申请, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axiosWrapper.delete(`/api/leaveRequests/${row.id}`)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.fetchLeaveRequests();
                        })
                        .catch(error => {
                            console.error('Error deleting leave request:', error);
                            this.$message.error('删除请假申请失败');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            saveLeaveRequest() {
                axiosWrapper.post('/api/leaveRequests/saveOrUpdate', this.currentLeaveRequest)
                    .then(() => {
                        this.$message({
                            type: 'success',
                            message: '请假申请保存成功!'
                        });
                        this.dialogVisible = false;
                        this.fetchLeaveRequests();
                    })
                    .catch(error => {
                        console.error('Error saving leave request:', error);
                        this.$message.error('保存请假申请失败');
                    });
            },
            handleSelectionChange(val) {
                this.selectedLeaveRequests = val;
            },
            handleBatchDelete() {
                if (this.selectedLeaveRequests.length === 0) {
                    this.$message.warning('请选择要删除的请假申请');
                    return;
                }
                this.$confirm(`此操作将永久删除选中的 ${this.selectedLeaveRequests.length} 个请假申请, 是否继续?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const ids = this.selectedLeaveRequests.map(leaveRequest => leaveRequest.id);
                    axiosWrapper.delete('/api/leaveRequests/batch', {data: ids})
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '批量删除成功!'
                            });
                            this.fetchLeaveRequests();
                        })
                        .catch(error => {
                            console.error('Error batch deleting leave requests:', error);
                            this.$message.error('批量删除请假申请失败');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            approveLeaveRequest(row) {
                this.$confirm('确定批准该请假申请吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const approveTime = new Date().toISOString();
                    const approverId = this.userInfo.id;
                    const updatedRow = {
                        ...row,
                        status: 'approved',
                        approveTime: approveTime,
                        approverId: approverId
                    };
                    axiosWrapper.post('/api/leaveRequests/saveOrUpdate', updatedRow)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '批准成功!'
                            });
                            this.fetchLeaveRequests();
                        })
                        .catch(error => {
                            console.error('Error approving leave request:', error);
                            this.$message.error('批准请假申请失败');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消批准'
                    });
                });
            },
            rejectLeaveRequest(row) {
                this.$confirm('确定拒绝该请假申请吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    const approveTime = new Date().toISOString();
                    const approverId = this.userInfo.id;
                    const updatedRow = {
                        ...row,
                        status: 'rejected',
                        approveTime: approveTime,
                        approverId: approverId
                    };
                    axiosWrapper.post('/api/leaveRequests/saveOrUpdate', updatedRow)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '拒绝成功!'
                            });
                            this.fetchLeaveRequests();
                        })
                        .catch(error => {
                            console.error('Error rejecting leave request:', error);
                            this.$message.error('拒绝请假申请失败');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消拒绝'
                    });
                });
            },
            getUserInfo() {
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                if (userInfo) {
                    this.userInfo = userInfo;
                    this.userRole = userInfo.role;
                }
            },
            fetchLeaveTypes() {
                const params = {
                    pageNum: 1,
                    pageSize: 9999
                };
                axiosWrapper.post('/api/leaveTypes/page', params)
                    .then(response => {
                        this.leaveTypes = response.data.list;
                    })
                    .catch(error => {
                        console.error('Error fetching leave types:', error);
                        this.$message.error('获取请假类型列表失败');
                    });
            }
        }
    });
</script>
</body>
</html>